import {Component, ElementRef, Inject, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {NgxEchartsService} from 'ngx-echarts';
import {ParentService} from "@train/parent/parent.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {SNSResult, StudentBodyDataVO, TrainOrgBodyDataCategoryVO} from "@interface/index";
import '@util/data/data.extensions';
import {ToolsService} from "@shared/service/tools/tools.service";
import {ActivatedRoute, Params, RouterModule} from "@angular/router";
import {SCRIPT_LOADER, ScriptLoader} from "@core/script-loader/script-loader";
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {forEach} from "@angular/router/src/utils/collection";
// import {SCRIPT_LOADER} from "../../../../app.module";
/**
 * @description 图表option
 * @author @chenwh576
 * @param {{yAxisMin: number; yAxisMax: number; yAxisName: string; data: Array<any[]>; name: string}} query
 * @return {{legend: {}; tooltip: {triggerOn: string; formatter: ((params) => string);
 * padding: [number , number , number , number]; textStyle: {color: string}; extraCssText: string};
 * toolbox: {show: boolean}; xAxis: {min: number; max: number; name: string; type: string;
 * axisLine: {onZero: boolean}}; yAxis: {min: number; max: number; name: string; type: string;
 * axisLine: {onZero: boolean}; splitLine: {show: boolean}}; series: [{type: string; data: Array<any[]>;
 * lineStyle: {normal: {color: string; borderColor: string; borderWidth: number}};
 * itemStyle: {normal: {borderWidth: number; borderColor: string; label: {show: boolean}}};
 * animationDelay: ((idx) => number)}]; animationEasing: string; animationDelayUpdate: ((idx) => number)}}
 * @constructor
 */
const GOUWUP_CHART_OPTIONS = (query: {
  yAxisMin: number,
  yAxisMax: number,
  yAxisName: string,
  data: Array<any[]>,
  name: string,
  splitNumber: number
}) => {
  return {
    legend: {},
    tooltip: {
      triggerOn: 'click',
      formatter: function (params) {
        return `${new Date(params.data[2]).format('yyyy-MM-dd')}<br>${query['name']}: ${params['data']['1']}${query['yAxisName']}<br>`
      },
      padding: [10, 10, 10, 10],
      textStyle: {
        color: '#4f4f4f',
      },
      extraCssText: 'background: white;box-shadow:0px 2px 5px rgba(0,0,0,0.1);',
      position: function (p, params, dom, rect, size) {
        let screenWidth = document.body.offsetWidth,
          left = screenWidth / 3,
          right = (screenWidth / 3) * 2;
        if (p[0] < left) {
          return [p[0] + 10, p[1] + 20];
        }
        if (left <= p[0] && p[0] <= right) {
          return [p[0] - size.contentSize[0] / 2, p[1] + 20]
        }
        if (p[0] > right) {
          return [p[0] - size.contentSize[0], p[1] + 20]
        }
      }
    },
    toolbox: {
      show: false
    },
    xAxis: {
      min: 0,
      max: 20,
      name: '岁',
      type: 'value',
      splitNumber: 9,
      axisLine: {
        onZero: false,
        lineStyle: {
          color: '#999999'
        }
      },
      splitLine: {
        lineStyle: {
          color: ['#e5e5e5'],
          type: 'dashed'
        }
      }
    },
    yAxis: {
      min: query.yAxisMin,
      max: query.yAxisMax,
      name: query.yAxisName,
      type: 'value',
      splitNumber: query.splitNumber,
      axisLine: {
        onZero: true,
        lineStyle: {
          color: '#999999'
        }
      },
      splitLine: {show: false}
    },
    series: [{
      type: 'line',
      data: query.data,
      symbolSize: 10,
      lineStyle: {
        normal: {
          color: '#23c270',
          borderColor: '#23c270',
          borderWidth: 2,
        },
      },
      itemStyle: {
        normal: {
          borderWidth: 2,
          borderColor: '#23c270',
          label: {
            show: false
          },
        },
      },
      animationDelay: function (idx) {
        return idx * 10;
      }
    }],
    animationEasing: 'elasticOut',
    animationDelayUpdate: function (idx) {
      return idx * 5;
    }
  };
};

@Component({
  selector: 'seed-grow-up',
  templateUrl: './grow-up.component.html',
  styleUrls: ['./grow-up.component.scss'],
  encapsulation: ViewEncapsulation.None
})


export class TrainChildGrowUpComponent implements OnInit {
  public tabs: Array<{}>;
  public options: Object;
  private _height: Array<number[]> = [];
  private _weight: Array<string[]> = [];
  private _standingReach: Array<string[]> = [];
  private _wingspan: Array<string[]> = [];
  public echartsIntance: any;
  public showChart: boolean = false;
  public tabOpen: boolean = false;
  public selectedTab = {
    yAxisMin: 0,
    yAxisMax: 0,
    yAxisName: '',
    data: null,
    name: '',
    splitNumber: 0
  };
  public resultEchartsObjList = [];
  public categoryId: number;

  constructor(
    private _parentService: ParentService,
    private _authService: AuthService,
    private _tools: ToolsService,
    private _route: ActivatedRoute,
    @Inject(SCRIPT_LOADER) public scriptLoader: ScriptLoader,
    private imageServe: ImageServeService
  ) {
    this._route.params
      .subscribe((params: Params) => {
        const studentId = params['studentId'];
        this.categoryId = +params['categoryId'];
        let data = this.fetchStudentBodyData(studentId),
          script = this.scriptLoader.load('echarts');
        Promise.all([script, data]).then(res => {
          if (res['0']['0']['loaded']) {
            this.showChart = true;
            this.formatStudentBodyData(res[1].data);
          }
        })
      });
  }

  getIcon(name: string): string {
    return this.imageServe.getIcon(name);
  }

  // 学员身高
  get height(): Array<any[]> {
    return this._height;
  }

  set height(value: Array<any[]>) {
    this._height = value;
  }

  // 学员体重
  get weight(): Array<any[]> {
    return this._weight;
  }

  set weight(value: Array<any[]>) {
    this._weight = value;
  }

  // 学员站立摸高
  get standingReach(): Array<any[]> {
    return this._standingReach;
  }

  set standingReach(value: Array<any[]>) {
    this._standingReach = value;
  }

  // 学员臂展
  get wingspan(): Array<any[]> {
    return this._wingspan;
  }

  set wingspan(value: Array<any[]>) {
    this._wingspan = value;
  }

  ngOnInit() {
  }

  /**
   * @description 根据学员Id 获取学员身体数据
   * @author @chenwh576
   * @param {number} studentId
   * @date 2018/3/5 下午2:53
   */
  fetchStudentBodyData(studentId: number): Promise<SNSResult<StudentBodyDataVO[]>> {
    const orgUserId = this._authService.getAuthOrgId();
    return this._parentService.fetchStudentBodyDate(orgUserId, studentId).toPromise()
  }

  /**
   * @description 根据获取到的学员数据组装学员身体数据
   * @author @chenwh576
   * @date 2018/3/5 下午2:56
   * @param {StudentBodyDataVO[]} data
   */
  formatStudentBodyData(data) {
    if (data.length > 0) {
      data.forEach((categoryItem) => {
        if (categoryItem) {
          let category = categoryItem.category,
            dataDetails = categoryItem.dataDetails,
            resultObj = Object.assign({}, this.selectedTab),
            data = [];
          category.categoryId !== undefined && (resultObj['categoryId'] = category.categoryId);
          category.categoryName !== undefined && (resultObj['name'] = category.categoryName);
          category.echartMinValue !== undefined && (resultObj['yAxisMin'] = category.echartMinValue);
          category.echartMaxValue !== undefined && (resultObj['yAxisMax'] = category.echartMaxValue);
          category.unitName !== undefined && (resultObj['yAxisName'] = category.unitName);
          category.echartSection !== undefined && (resultObj['splitNumber'] = category.echartSection);

          if (dataDetails.length > 0) {
            dataDetails.forEach((dataItem) => {
              let dataItemArr = [];
              dataItem.recordAge !== undefined && dataItemArr.push(dataItem.recordAge);
              dataItem.studentBodyData.dataValue !== undefined && dataItemArr.push(dataItem.studentBodyData.dataValue);
              dataItem.studentBodyData.createTime !== undefined && dataItemArr.push(dataItem.studentBodyData.createTime);
              data.push(dataItemArr)
            });
            resultObj['data'] = data;
            this.resultEchartsObjList.push(resultObj);
          }
          if (resultObj['categoryId'] === this.categoryId) {
            this.selectedTab = resultObj;
          }
        }
      });
      this.showECharts();
    }
  }

  /**
   * @author guoqs1331
   * @time 2018/3/30
   * @description
   */
  changeCategory(item) {
    this.selectedTab = item;
    this.showECharts();
    this.tabOpen = !this.tabOpen;
  }

  /**
   * @author guoqs1331
   * @time 2018/3/31
   * @description showEcharts
   */
  showECharts() {
    this.options = GOUWUP_CHART_OPTIONS(this.selectedTab);
    if (!this.selectedTab['data']) {
      this._tools.showToast('暂无数据', 800);
      return;
    }
  }

  /**
   * @author guoqs1331
   * @time 2018/3/30
   * @description
   */
  closeTabs() {
    this.tabOpen = !this.tabOpen;
  }

  onChartInit(e) {
    this.echartsIntance = e;
  }

}

